﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAAC.DTO;
using SAAC.DAL;
using System.Security.Cryptography;


namespace SAAC.BLL
{
    public class UsuarioBLL
    {
        protected UsuarioDAL _usuarioDAL;

        public UsuarioBLL()
        {
            if (_usuarioDAL == null)
                _usuarioDAL = new UsuarioDAL();
        }

        public UsuarioDTO Select(UsuarioDTO dto, string order = null)
        {
            try
            {
				if (dto.Senha != null && !dto.IsSenhaHash)
				{
					dto.Senha = GetHashString(dto.Senha);
					dto.IsSenhaHash = true;
				}
                return _usuarioDAL.Select(dto, order);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public List<UsuarioDTO> SelectAll(UsuarioDTO dto, string order = null, int limit = 1000)
        {
            try
            {
				if (dto.Senha != null && !dto.IsSenhaHash)
				{
					dto.Senha = GetHashString(dto.Senha);
					dto.IsSenhaHash = true;
				}
                return _usuarioDAL.SelectAll(dto, order, limit);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Insert(UsuarioDTO dto)
        {
            try
            {
				if (dto.Senha != null && !dto.IsSenhaHash)
				{
					dto.Senha = GetHashString(dto.Senha);
					dto.IsSenhaHash = true;
				}
                _usuarioDAL.Insert(dto);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Update(UsuarioDTO dto)
        {
            try
            {
				if (dto.Senha != null && !dto.IsSenhaHash)
				{
					dto.Senha = GetHashString(dto.Senha);
					dto.IsSenhaHash = true;
				}
                _usuarioDAL.Update(dto);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Delete(UsuarioDTO dto)
        {
            try
            {
                _usuarioDAL.Delete(dto);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

		public static byte[] GetHash(string inputString)
		{
			HashAlgorithm algorithm = SHA1.Create();
			return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
		}

		public static string GetHashString(string inputString)
		{
			StringBuilder sb = new StringBuilder();
			foreach (byte b in GetHash(inputString))
				sb.Append(b.ToString("X2"));

			return sb.ToString();
		}
    }
}
